package com.wg.neptune.cluster.strategy;

import com.wg.neptune.cluster.Cluster;
import com.wg.neptune.cluster.util.RandomUtil;
import com.wg.neptune.model.ProviderService;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by mc on 18/6/6.
 */
public class WeightRandomClusterStrategy implements Cluster {

    /**
     * 基于权重负载均衡算法:根据权重复制，如果权重为3，providerServiceList出现三个一样的ProviderService
     * @param providerServices
     * @return
     */
    public ProviderService select(List<ProviderService> providerServices) {

        if(providerServices.size() <= 0){
            return null;
        }
        List<ProviderService> providerServiceList = new ArrayList<ProviderService>();
        for(ProviderService providerService : providerServices){
            for(int i = 0 ; i < providerService.getWeight() ; i++) {
                providerServiceList.add(providerService.copy());
            }
        }
        int length = providerServiceList.size();
        int index = RandomUtil.getRandomNum(length-1);
        return providerServices.get(index);
    }
}
